package com.xian.ucenter.aop;

import com.xian.ucenter.utils.ConstantUtil;
import com.xian.ucenter.utils.RedisUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class PostViewCount {
    @Autowired
    private RedisUtil redisUtil;
    @Pointcut("@annotation(com.xian.ucenter.annotation.PostView)")
    public void postViewCount(){}
    @Pointcut("@annotation(com.xian.ucenter.annotation.WebView)")
    public void webViewCount(){}

    @After("postViewCount()")
    public void afterViewPost(JoinPoint point) {
        Object[] args = point.getArgs();
        String postId = (String) args[0];
        redisUtil.zIncrementScore(ConstantUtil.POST_VIEW_KEY, postId, 1);
    }

    @After("webViewCount()")
    public void afterViewWeb(JoinPoint point) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String remoteHost = getRemoteHost(request);
        redisUtil.pfAdd(ConstantUtil.WEB_VIEW_KEY, remoteHost);
    }

    public String getRemoteHost(HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
    }
}
